<template>
  <el-form
    ref="registerForm"
    :model="registerForm"
    class="forgot-pwd-form"
    label-width="110px"
    label-position="right"
    :rules="rules">
    <el-form-item label="账号" prop="email">
      <el-input
        v-model="registerForm.email"
        size="small"
        placeholder="请输入邮箱">
      </el-input>
    </el-form-item>
    <el-form-item label="验证码" prop="code">
      <el-input
        v-model="registerForm.code"
        size="small"
        placeholder="请输入验证码">
      </el-input>
      <el-button :disabled="countdown > 0" class="obtain-code" @click="handleCode">
        <!-- 显示倒计时或获取验证码 -->
        {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
      </el-button>
    </el-form-item>
    <el-form-item label="登录密码" prop="password">
      <template #label>
        <span>登录密码</span>&nbsp;
        <el-tooltip content="密码必须同时包含大小写英文和数字，长度:8-64" placement="top">
          <i class="iconfont icon-wenhao"></i>
        </el-tooltip>
      </template>
      <input type="password" style="display: none;" autocomplete="new-password">
      <el-input
        v-model="registerForm.password"
        :type="passwordType"
        size="small"
        placeholder="请设置登录密码">
        <i slot="suffix" class="el-icon-view el-input__icon" @click="showPassword" />
      </el-input>
    </el-form-item>
    <el-form-item label="确认登录密码" prop="confirmPassword">
      <el-input
        v-model="registerForm.confirmPassword"
        :type="confirmPasswordType"
        size="small"
        placeholder="请再次输入设置登录密码">
        <i slot="suffix" class="el-icon-view el-input__icon" @click="showConfirmPassword" />
      </el-input>
    </el-form-item>
    <el-form-item label="您的姓名" prop="name">
      <el-input
        v-model="registerForm.name"
        size="small"
        placeholder="请输入姓名"
        maxlength="20">
      </el-input>
    </el-form-item>
    <el-form-item v-if="website.validateCode" prop="code">
      <Verify
        ref="verify"
        :mode="'pop'"
        :captcha-type="'blockPuzzle'"
        :img-size="{ width: '330px', height: '155px' }"
        @success="verifySuccess" />
    </el-form-item>
    <el-button type="primary" size="small" class="login-submit" @click.native.prevent="handleRegister">注册
    </el-button>
    <div class="login-tips">已有账号？<span class="jump-login" @click="jumpLogin">去登录</span></div>
  </el-form>
</template>

<script>
import { getTenantId } from '@/api/login'
import { register, emailCode } from '@/api/admin/user'
import { mapGetters } from 'vuex'
import { setStore } from '@/util/store'
import { mapMutations } from 'vuex'
import { Base64 } from 'js-base64'
import Verify from '@/components/verifition/Verify'
export default {
  name: 'userRegister',
  components: {
    Verify
  },
  data() {
    return {
      registerForm: {
        email: '', // 邮箱账号
        code: '', // 邮箱验证码
        password: '', // 密码
        confirmPassword: '', // 再次确认密码
        name: '' // 姓名
      },
      rules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: this.validateEmail, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请设置登录密码', trigger: 'blur' },
          { min: 8, max: 64, message: '请输入规范的密码', trigger: 'blur' },
          { validator: this.validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入设置登录密码', trigger: 'blur' },
          { min: 8, max: 64, message: '请输入规范的密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 1, max: 20, message: '请输入姓名', trigger: 'blur' },
          { validator: this.validateName, trigger: 'blur' }
        ]
      },
      passwordType: 'password',
      confirmPasswordType: 'password',
      countdown: 0, // 倒计时秒数
      initialCountdown: 60, // 倒计时初始值，根据需要可以调整这个值
      verifycode: '' // 图形验证码
    }
  },
  computed: {
    ...mapGetters(['tagWel', 'website']),
    ...mapMutations(['SET_ACCESS_TOKEN'])
  },
  methods: {
    // 邮箱校验
    validateEmail(rule, value, callback) {
      const flag = new RegExp(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/).test(value)
      if (!flag) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    },
    // 密码校验
    validatePassword(rule, value, callback) {
      const flag = new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z0-9!@#$%^&*()\-_=+[\]{}|\\:;"'<>,.?/~`]+$/).test(value)
      if (!flag) {
        callback(new Error('请输入规范的密码'))
      } else {
        callback()
      }
    },
    // 确认密码校验
    validateConfirmPassword(rule, value, callback) {
      if (value === this.registerForm.password) {
        callback()
      } else {
        callback(new Error("两次输入的密码不一致"))
      }
      const flag = new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z0-9!@#$%^&*()\-_=+[\]{}|\\:;"'<>,.?/~`]+$/).test(value)
      if (!flag) {
        callback(new Error('请输入规范的密码'))
      } else {
        callback()
      }
    },
    // 姓名
    validateName(rule, value, callback) {
      if (value.trim() === '') {
        callback(new Error('请输入姓名'))
      } else {
        callback()
      }
    },
    showPassword() {
      this.passwordType === ''
        ? (this.passwordType = 'password')
        : (this.passwordType = '')
    },
    showConfirmPassword() {
      this.confirmPasswordType === ''
        ? (this.confirmPasswordType = 'password')
        : (this.confirmPasswordType = '')
    },
    // 获取图形验证
    handleCode() {
      this.$refs.registerForm.validateField('email', (errorMsg) => {
        if (errorMsg) {
          // errorMsg 将会是你在 rules 中设定的消息，这里我们不需要做额外的事情
        } else {
          // 如果验证通过，那么执行获取验证码的逻辑
          this.$refs.verify.show()
        }
      })
    },
    verifySuccess(params) {
      this.verifycode = params.captchaVerification
      this.handleObtainCode()
    },
    // 获取邮箱验证码
    handleObtainCode() {
      const params = {
        email: this.registerForm.email,
        type: 'register',
        code: this.verifycode,
        randomStr: 'blockPuzzle'
      }
      emailCode(params).then(res => {
        // 假设以下是 API 调用成功后的回调部分
        this.$message.success('验证码发送成功')
        this.countdown = this.initialCountdown // 初始化倒计时
        const intervalId = setInterval(() => {
          if (this.countdown > 0) {
            this.countdown -= 1 // 减少倒计时
          } else {
            clearInterval(intervalId) // 清除定时器
          }
        }, 1000) // 每1000毫秒（1秒）执行一次
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    /**
     * 邮箱注册
     */
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          const params = {
            email: this.registerForm.email,
            code: this.registerForm.code,
            password: Base64.encode(this.registerForm.password),
            name: this.registerForm.name.trim()
          }
          register(params).then(res => {
            this.$message.success('注册成功!')
            this.$store.commit('SET_ACCESS_TOKEN', res.data.data.access_token)
            this.$store.commit('SET_REFRESH_TOKEN', res.data.data.refresh_token)
            setTimeout(() => {
              this.$router.push({ path: '/wel' })
            }, 100)
          }).catch(err => {
            this.$message.error(err.message)
          })
        } else {
          return false
        }
      })
    },
    // 跳转至登录页
    jumpLogin() {
      this.$emit('change', 'user')
    },
    queryTenantId() {
      const params = {
        username: this.registerForm.email
      }
      getTenantId(params).then((res) => {
        // 写入到 sessionStore 方便 axios 每次请求获取 tab 范围内的租户ID
        setStore({ name: 'tenantId', content: res.data.data, type: 'session' })
        // 写入到 localStore 方便 下次登录回显上次选择的租户ID
        setStore({ name: 'tenantId', content: res.data.data })
        const params = {
          username: this.registerForm.email,
          password: this.registerForm.password,
          code: '',
          randomStr: 'blockPuzzle'
        }
        this.$store.dispatch('LoginByUsername', Object.assign({}, params)).then(() => {
          this.$router.push({ path: this.tagWel.value })
        }).catch(err => {
          this.$message.error(err.message)
        })
      }).catch(err => {
        this.$message.error(err.message)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.obtain-code {
  border: 0 !important;
  background: transparent !important;
  border-left: 1px solid #DCDFE6 !important;
  padding-left: 10px;
  right: 0;
  &.is-disabled {
    color: #C0C4CC !important;
  }
}
.login-tips {
  color: #333;
  margin-top: 20px;

  .jump-login {
    color: #275FE8;
    font-size: 14px;
    cursor: pointer;
  }
}
::v-deep .el-form-item .el-form-item__content .mask + .el-form-item__error {
  display: none !important;
}
</style>
